<template>
	<view>
		<view class="address-container">
			<view class="from">
				<text>{{ from.address }}</text>
			</view>
			<view class="dashed-line"></view>
			<view class="to">
				<text>{{ to.address }}</text>
			</view>
		</view>
		<view v-if="inPorcessOrderId != null" class="order-process" @click="toInProcessOrder">您有进行中的订单,点击查看</view>
		<map
			id="map"
			:longitude="from.longitude"
			:latitude="from.latitude"
			:style="contentStyle"
			scale="14"
			:enable-traffic="false"
			:show-location="true"
			class="map"
			:polyline="polyline"
			:markers="markers"
		></map>

		<view class="panel">
			<view class="row">
				<view class="info">
					<view class="label">全程</view>
					<view class="value">
						<text>{{ distance }}</text>
						公里
					</view>
					<view class="label">，预计</view>
					<view class="value">
						<text>{{ duration }}</text>
						分钟
					</view>
				</view>
				<view class="opt" @tap="chooseCarHandle" v-if="!showCar">选择车辆</view>
				<view class="opt" @tap="chooseCarHandle" v-if="showCar">{{ car.carType }}{{ car.carPlate }}</view>
			</view>
			<button class="btn" @tap="createOrderHandle">呼叫代驾</button>
		</view>
		<u-popup v-model="showPopup" mode="center" width="600" height="280" :mask-close-able="false">
			<view class="popup-title">您的订单正在等待司机接单</view>
			<view class="count-down">
				<u-count-down
					ref="uCountDown"
					:timestamp="timestamp"
					:autoplay="false"
					separator="zh"
					:show-hours="false"
					:show-border="true"
					bg-color="#DDF0FF"
					separator-color="#0083F3"
					border-color="#0D90FF"
					color="#0D90FF"
					font-size="32"
					@end="countDownCancelHandle"
					@change="countChangeHandle"
				></u-count-down>
				
			</view>
			<button class="btn" @tap="countDownCancelHandle">取消订单</button>
		</u-popup>
		
		<u-top-tips ref="uTips"></u-top-tips>
		<u-modal v-model="uModalShow" 
		show-confirm-button="继续等待"
		show-cancel-button="确定取消"
		@confirm="confirm" ref="uModal" :async-close="true"></u-modal>

	</view>
</template>

<script>
let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
let qqmapsdk;
export default {
	data() {
		return {
			//订单路线：开始位置和结束位子
			from: {
				address: '',
				longitude: 0,
				latitude: 0
			},
			to: {
				address: '',
				longitude: 0,
				latitude: 0
			},
			//窗口样式
			contentStyle: '',
			windowHeight: 0,
			//距离和时长
			distance: 0,
			duration: 0,
			//路线规划，路线坐标和图标
			polyline: [],
			markers: [],
			
			//
			infoStatus: true,
			car:{
				//乘客选择的车辆
				carId: null,
				carPlate: null,
				carType: null,
			},
			showCar: false,
			showPopup: false,
			timestamp: 60,
			timestampStaring:false,
			orderNo: null,
			//地图组件
			map:null,
			//接单的定时任务
			acceptOrderTimer:null,
			uModalShow:false,
			//是否有进行中的订单
			inPorcessOrderId:null
		};
	},
	methods: {
		//呼叫代驾时监听订单是否被接
		countChangeHandle(){
			const _this =this;
			_this.post('order/app/order/info/'+_this.orderNo,(res)=>{
				const {success,data,message}=res.data
				if(success && data.status==_this.Consts.OrderStatus.ORDER_STATUS_ACCEPTED){
					_this.showPopup=false;
					_this.timestamp=0;
					uni.navigateTo({
						url:'/pages/move/move?orderNo='+_this.orderNo
						
					})
				}
			})
			
		},
		//查看正在进行中的订单
		toInProcessOrder(){
			const _this=this;
			const order =uni.getStorageSync("order")
			//等待接单状态
			if(order.status==_this.Consts.OrderStatus.ORDER_STATUS_WAIT){
				// uni.navigateTo({
				// 	url:'/pages/create_order/create_order?orderNo='+order.orderNo
				// })
				//重新计算接单时间
				//接单时间 + 60 -当前时间 >0  显示倒计时
			    //接单时间 + 60 -当前时间 <0 订单取消
				// debugger;
				 const overTime =new Date(order.createTime).getTime() +60000 //超时时间
				 const nowTime =new Date().getTime(); //获取当前时间时间戳
				 const timeStamp = overTime- nowTime;
				 if(timeStamp>0){ 
					 _this.timestamp=timeStamp/1000
					 _this.showPopup=true;
					 this.$refs.uCountDown.start();
					 //在_this.timeStamp时间后，执行setTimeout里面的方法
					//  setTimeout(() => {
					// }, _this.timeStamp)
			 }
			}
			//已接单状态 
			else if(order.status==_this.Consts.OrderStatus.ORDER_STATUS_ACCEPTED
				 ||order.status==_this.Consts.OrderStatus.ORDER_STATUS_ARRIVE
				 ||order.status==_this.Consts.OrderStatus.ORDER_STATUS_START_DRIVING)
			{
				//跳转到司乘同显页面
				uni.navigateTo({
					url:'/pages/move/move?orderNo='+order.orderNo
				})
			}
			//未付款状态
			else if(order.status==_this.Consts.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED
				 ||order.status==_this.Consts.OrderStatus.ORDER_STATUS_ENSURE
				 ||order.status==_this.Consts.OrderStatus.ORDER_STATUS_NOT_PAY)
			{
				//跳转到订单信息页
				uni.navigateTo({
					url:'/pages/order/order?orderNo='+order.orderNo
				})
			}
		},
		//查询是否有正在进行中的订单
		queryProcessingOrder(){
			const _this = this;
			_this.get("order/app/order/queryProcessingOrder",(res)=>{
				const {data,success}=res.data
				if(success && data){
					_this.inPorcessOrderId=data.orderNo
					uni.setStorageSync("order",data)
				}
			})
		},
		//取消订单
		countDownCancelHandle(){
			const _this =this;
			_this.showPopup=false;
			//需要重置为0，否则重新载入不会显示倒计时框
			_this.timestamp=0
			if(_this.orderNo !=null){
				_this.post("order/app/order/cancelOrder/"+_this.orderNo,(res)=>{
					const {success,data}=res.data
					if(success){
						uni.showToast({
							icon:"success",
							title:"取消订单成功！"
						})
					}else{
						uni.showToast({
							icon:"error",
							title:"网络异常！"
						})
					}
				})
			}else if (_this.orderNo ==null){
				const order=uni.getStorageSync("order")
				_this.post("order/app/order/cancelOrder/"+order.orderNo,(res)=>{
					const {success,data}=res.data
					if(success){
						uni.showToast({
							icon:"success",
							title:"取消订单成功！"
						})
						uni.removeStorageSync("order")
						_this.inPorcessOrderId=null;
					}else{
						uni.showToast({
							icon:"error",
							title:"网络异常！"
						})
					}
				})
			}
		
			
		},
		//创建订单
		createOrderHandle(){
			const _this =this;
			_this.timestamp=60
			//呼叫司机 准备计算价格
			let param={
				startPlace: _this.from.address,
				endPlace: _this.to.address,
				expectsMileage: _this.distance,
				carPlate: _this.car.carPlate,
				carType: _this.car.carType,
				expectMinutes: _this.duration,
				startPlaceLongitude: _this.from.longitude,
				startPlaceLatitude: _this.from.latitude,
				endPlaceLongitude: _this.to.longitude,
				endPlaceLatitude: _this.to.latitude
			}
			const car =uni.getStorageSync("car")
			if(_this.showCar){
				_this.post("order/app/order/createOrder",param,(res)=>{
					const {success,data}=res.data
					if(success){
						//获得订单编号
						_this.orderNo= data
						_this.showPopup=true;
						//进行 倒计时
						setTimeout(() => {
							this.$refs.uCountDown.start();
						}, _this.timeStamp)
					}else{
						uni.showToast({
							icon:'error',
							title:'创建订单失败'
						})
					}
				})
			}else{
				uni.showToast({
					icon:'error',
					title:'请选择车辆'
				})
			}
			
		},
		chooseCarHandle(){
			uni.navigateTo({
				url:'/pages/car_list/car_list'
			})
			
		},
		//初始化窗口样式
		initStyle(){
			let _this = this;
			//处理窗口样式
			let windowHeight = uni.getSystemInfoSync().windowHeight;
			_this.windowHeight = windowHeight;
			_this.contentStyle = `height:${_this.windowHeight}px;`;
		},
		//初始化地图
		initMap(){
			let _this = this;
			//腾讯地图
			qqmapsdk = new QQMapWX({
			    key: _this.Consts.QQMAP_KEY
			}); 
			//uniapp地图
			_this.map = uni.createMapContext("map", this);
		},
		//画规划路线
		drawLine(){
			var _this = this;
			const fromtoParam = uni.getStorageSync("fromtoParam")
			_this.from=fromtoParam.from
			_this.to=fromtoParam.to
			
			//在Page({})中使用下列代码
			//触发表单提交事件，调用接口
			//调用距离计算接口
			qqmapsdk.direction({
			  mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
			  //from参数不填默认当前地址
			  from: _this.from,
			  to: _this.to,
			  success: function (res) {
				var ret = res;
				_this.distance=(ret.result.routes[0].distance/1000).toFixed(2)
				_this.duration=ret.result.routes[0].duration
				var coors = ret.result.routes[0].polyline, pl = [];
				//坐标解压（返回的点串坐标，通过前向差分进行压缩）
				var kr = 1000000;
				for (var i = 2; i < coors.length; i++) {
				  coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
				}
				//将解压后的坐标放入点串数组pl中 【经纬度数组】
				for (var i = 0; i < coors.length; i += 2) {
				  pl.push({ latitude: coors[i], longitude: coors[i + 1] })
				}
				//路线属性
				_this.polyline=[{
					'points':pl,
					'color':'#FF0000DD',
					'width':3,
					'dottedLine':true,//是否虚线
					'arrowLine':true //带箭头的线
				}]
				//起始点属性
				_this.markers=[
				{
					'id':1,
					'longitude': _this.from.longitude,
					'latitude': _this.from.latitude,
					'iconPath':'/static/order/start.png',
					'width':35,
					'height':50
					
				},
				{
					'id':2,
					'longitude': _this.to.longitude,
					'latitude': _this.to.latitude,
					'iconPath':'/static/order/end.png',
					'width':35,
					'height':50
					
				}]
				//官网代码：但我们不是这么玩的↓
				//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
				// _this.setData({
				//   latitude:pl[0].latitude,
				//   longitude:pl[0].longitude,
				//   polyline: [{
				// 	points: pl,
				// 	color: '#FF0000DD',
				// 	width: 4
				//   }]
				// })
				
				
			  },
			  fail: function (error) {
			  },
			  complete: function (res) {
			  }
			});
			
			
		},
	},
	onLoad: function(options) {
		let _this = this;
		_this.initStyle();
		_this.initMap();
		//拿到位置信息
		_this.from = uni.getStorageSync("from");
		_this.to = uni.getStorageSync("to");
		_this.drawLine();
	},
	onShow: function() {
		let _this = this;
		//回填车辆
		let car = uni.getStorageSync("car");
		if(car){
			_this.showCar = true;
			_this.car = car;
		};
		_this.queryProcessingOrder()
	},
	onUnload() {
		const _this = this;
		_this.drawLine();
	}
};
</script>

<style lang="less">
@import url('create_order.less');

</style>
